#include "globals.h"
#include "scan.h"
#include "parse.h"
#include "util.h"
#include "analyze.h"
#include "cgen.h"

int lineno=0;
FILE * source;
FILE * listing;
FILE * code;

int main(int argc, char *argv[]){
  TreeNode *syntaxTree;
  char pgm[120];
  
  if(argc != 2){
    printf("Error: argv!\n");
    return 1;
  }
  strcpy(pgm,argv[1]);
  
  if((source=fopen(argv[1],"r"))==NULL){
    printf("Error: file can't open!\n");
    return 1;
  }
  listing=stdout;
  
  //while(getToken()!=ENDFILE);
  // printf("============reach\n");
  
  syntaxTree=parse();
  
  printf("\nSyntax tree:\n");
  printTree(syntaxTree);
  
  printf("\nBuilding Symbol Table...\n");
  buildSymtab(syntaxTree);
  printSymTab(listing);
  
  printf("\nChecking Types...\n");
  typeCheck(syntaxTree);
  printf("\nType Checking Finished\n");

  char * codefile;
  int fnlen = strcspn(pgm,".");
  codefile=(char*)calloc(fnlen+4,sizeof(char));
  strncpy(codefile,pgm,fnlen);
  strcat(codefile,".tm");
  code=fopen(codefile,"w");
  if(code==NULL){
    printf("can't open %s\n",codefile);
    exit(1);
  }
  codeGen(syntaxTree,codefile);
  fclose(source);
  return 0;
}
